package com.gaga.console.core.service.impl;

import com.gaga.common.constant.Constants;
import com.gaga.common.exception.CaptchaException;
import com.gaga.common.result.Result;
import com.gaga.console.base.utils.ECacheUtil;
import com.gaga.console.core.service.AuthService;
import com.wf.captcha.ArithmeticCaptcha;

import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 验证码业务类
 * @author pangu
 */
@Slf4j
@Service
@AllArgsConstructor
public class AuthServiceImpl implements AuthService {


    @Override
    public Result getCode() {
        Map<String, String> data = new HashMap<>(2);
        String uuid = UUID.randomUUID().toString().replace("-","");
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 40);
        captcha.getArithmeticString();
        // 获取运算的结果：5
        String text = captcha.text();
        data.put("key", uuid);
        data.put("codeUrl", captcha.toBase64());

        ECacheUtil.put(Constants.CAPTCHA_CODE_KEY, uuid, text);

        return Result.ok(data);
    }

    @Override
    public void check(String codeUuid, String code) throws CaptchaException {

        if (StrUtil.isBlank(code)) {
            throw new CaptchaException("请输入验证码");
        }
        String captcha = (String) ECacheUtil.get(Constants.CAPTCHA_CODE_KEY, codeUuid, String.class);
        ECacheUtil.remove(Constants.CAPTCHA_CODE_KEY, codeUuid);

        if (captcha == null) {
            throw new CaptchaException("验证码已过期");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException("验证码不正确");
        }

//        if (codeFromRedis == null) {
//            throw new CaptchaException("验证码已过期");
//        }
//        if (!StrUtil.equalsIgnoreCase(code, codeFromRedis.toString())) {
//            throw new CaptchaException("验证码不正确");
//        }

    }
}
